package com.hzlj.position.dbsync.liaoning.rest;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fz.common.base.core.JsonUtils;
import com.fz.common.base.core.date.DateUtils;
import com.hzlj.position.dbsync.liaoning.config.LnSqjzConfig;
import com.hzlj.position.locate.common.dto.position.PositionHandleDTO;
import com.hzlj.position.locate.dao.PositionDao;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LnSqjzRest {
    private static PositionDao positionDao;
    private static LnSqjzConfig lnSqjzConfig;

    public LnSqjzRest(LnSqjzConfig lnSqjzConfig,
                      PositionDao positionDao) {
        LnSqjzRest.lnSqjzConfig = lnSqjzConfig;
        LnSqjzRest.positionDao = positionDao;
    }

    /**
     * 只处理越界数据
     */
    public void positionHandle(PositionHandleDTO dto) {
        List<HandleDTO> handles = HandleDTO.from(dto);
        for (HandleDTO handle : handles) {
            log.info("发送异常处理数据:handle={}", JsonUtils.obj2json(handle));
            HttpRequest request = HttpRequest.post(lnSqjzConfig.getUrl() + "/viewAlarminfo/locAlarmDealWith")
                    .body(JsonUtils.obj2json(handle));
            try (HttpResponse execute = request.execute()) {
                String body = execute.body();
                HandleResponse result = JsonUtils.json2obj(body, HandleResponse.class);
                if (!result.success()) {
                    log.error("发送异常处理数据失败:handle={},result={}", handle, result);
                }
            } catch (Exception e) {
                log.error("发送异常处理数据失败:handle={}", handle, e);
            }
        }
    }


    @Data
    @NoArgsConstructor
    @Accessors(chain = true)
    public static class HandleDTO {
        @JsonProperty("signature")
        private String signature;
        @JsonProperty("jlnr")
        private String jlnr;
        @JsonProperty("bz")
        private String bz;
        @JsonProperty("clrxm")
        private String clrxm;
        @JsonProperty("bjid")
        private String bjid;
        @JsonProperty("nonce")
        private String nonce;
        @JsonProperty("clsj")
        private String clsj;
        @JsonProperty("username")
        private String username;
        @JsonProperty("timestamp")
        private String timestamp;

        public static List<HandleDTO> from(PositionHandleDTO dto) {
            return dto.getKeys().stream().map(e -> {
//                PositionQueryResultDTO position = positionDao.getPosition(e.getId(), e.getPositionTime());
//                if (position == null) {
//                    return null;
//                }
//                //只处理越界数据
//                if (!WarningType.isCrossWithHandle(position.getWarningType())) {
//                    return null;
//                }
                HandleDTO handle = new HandleDTO();
                handle.setJlnr(dto.getHandleExt().getHandleReason());
                handle.setBz(dto.getHandleExt().getHandleRemark());
                handle.setClrxm(dto.getHandleExt().getHandlerName());
                handle.setBjid(e.getId());
                handle.setNonce(UUID.randomUUID().toString(true));
                handle.setClsj(DateUtils.formatDate(dto.getHandleTime()));
                handle.setUsername(lnSqjzConfig.getUserName());
                handle.setTimestamp(System.currentTimeMillis() + "");
                //加密
                handle.setSignature(
                        toSHA256(handle.getTimestamp() + lnSqjzConfig.getKey() + handle.getNonce() + handle.getTimestamp())
                );
                return handle;
            }).filter(Objects::nonNull).collect(Collectors.toList());
        }
    }

    @Data
    @NoArgsConstructor
    public static class HandleResponse {
        @JsonProperty("code")
        private Integer code;
        @JsonProperty("desc")
        private String desc;

        public boolean success() {
            return 0 == code;
        }
    }

    @SneakyThrows
    public static String toSHA256(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
        encodeStr = byte2Hex(messageDigest.digest());
        return encodeStr;
    }

    private static String byte2Hex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        String temp;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                result.append("0");
            }
            result.append(temp);
        }
        return result.toString();
    }

    public static void main(String[] args) {
        LnSqjzRest lnSqjzRest = new LnSqjzRest(new LnSqjzConfig(), null);
        PositionHandleDTO dto = JsonUtils.json2obj(
                "{\"keys\":[{\"id\":\"1727150548005949441\",\"positionTime\":\"2023-11-22 10:22:34\"}],\"handleStatus\":\"2\",\"handleTime\":\"2024-02-27 11:10:05\",\"handleExt\":{\"handleReason\":\"经核查，矫正对象存在该异常，已教育\",\"handleRemark\":\"111\",\"handlerUid\":\"50d5da750ee345cd95dc811a5e6e7d76\"},\"normal\":false}",
                PositionHandleDTO.class
        );
        dto.getHandleExt().setHandlerName("test");
        lnSqjzRest.positionHandle(dto);
    }
}
